#pragma once
#include <iostream>
#include <memory>
#include <unistd.h>
#include "Socket.hpp"
#include <sys/poll.h>
using namespace LogMoudle;
using namespace SocketMoudle;
class PollServer
{
    const static int defaultd = -1;
    const static int size = 4096;

public:
    PollServer(uint16_t port)
        : _listensock(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listensock->BuildTcpSocketMethod(port);
        for (int i = 0; i < size; i++)
        {
            _fds[i].fd=defaultd;
            _fds[i].events=0;
            _fds[i].revents=0;
        }
          _fds[0].fd = _listensock->Fd();
          _fds[0].events=POLLIN;//关心读事件
    }
    void Start()
    {
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
             PrintFd();
            int n=poll(_fds,size,timeout);
            switch (n)
            {
            case -1:
                LOG(loglevel::ERROR) << "poll error";
                break;
            case 0:
                LOG(loglevel::DEBUG) << "poll time out...";
                break;
            default:
                // 有事件就绪,就不仅仅是新连接到来了吧？读事件就绪啊？
                LOG(loglevel::DEBUG) << "有事件就绪了..., n : " << n;
                Dispatcher(); // 处理就绪的事件
                break;
            }
        }
        _isrunning = false;
    }
    void Dispatcher()
    {
        for (int i = 0; i < size; i++)
        {
            if (_fds[i].fd == defaultd)
                continue;
            // fd合法，不一定就绪
            if (_fds[i].revents&POLLIN)
            {
                 if (_fds[i].fd == _listensock->Fd())
                {
                    // listensockfd 新连接到来
                    Acceptr();
                }
                else
                {
                    // 普通的读事件就绪
                    Recver(i);
                }
            }
        }
    }
    void Acceptr()//获取连接
    {
        InetAddr client;
        int fd = _listensock->Accept(&client);
        if (fd >= 0)
        {
            LOG(loglevel::INFO) << "get a new link, sockfd: "
                                << fd << ", client is: " << client.StringAddr();
            int pos = 0;
            for (; pos < size; pos++)
            {
                if (_fds[pos].fd == defaultd)
                {
                    break;
                }
            }
            if (pos == size)
            {
                //装满了
                LOG(loglevel::WARNING) << "poll server full";
                close(fd);
            }
            else
            {
                _fds[pos].fd = fd;
                _fds[pos].events=POLLIN;
                _fds[pos].revents=0;
            }
        }
    }
    void Recver(int pos) // 普通读取
    {
        char buffer[1024];
        ssize_t n = recv(_fds[pos].fd, buffer, sizeof(buffer)-1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@ " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(loglevel::INFO) << "clien quit...";
            // 1. 不要在关系这个fd了
            close(_fds[pos].fd);
            _fds[pos].fd = defaultd;
             _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
        else
        {
            LOG(loglevel::ERROR) << "recv error";
            // 2. 关闭fd
            close(_fds[pos].fd);
            // 1. 不要让select在关系这个fd了
            _fds[pos].fd = defaultd;
            _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
    }
    void PrintFd()
    {
        std::cout << "_fds[]:  ";
        for (int i = 0; i < size; i++)
        {
            if (_fds[i].fd == defaultd)
                continue;
            std::cout << _fds[i].fd << " ";
        }
        std::cout << "\r\n";
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~PollServer()
    {
    }

private:
    bool _isrunning;
    std::unique_ptr<Socket> _listensock;
    struct pollfd _fds[size];
};